import React, { useEffect, useState } from 'react';
import { Table, Button, Modal, Upload, message } from 'antd';
import { UploadOutlined , WarningOutlined } from '@ant-design/icons';
import { useMappedState, useDispatch } from 'redux-react-hook';

import style from "./user.module.less";

import EditForm from './EditForm';
import { PublicState } from '@@/store/reducers';
import {
  ac_get_allusers,
  ac_delete_user,
  ac_set_update_user
} from '@@/store/actions';
import { host } from '@@/utils/http';

// 分页配置
const pageConfig = {
  showSizeChanger: true, // 显示条目数选线
  pageSizeOptions: ['10', '20', '50'], // 每页条目数可选值
  defaultCurrent: 1, // 当前页
  total: 1 // 总条目数
}

const User = () => {
  const [ isModalVisible, setIsModalVisible ] = useState(false);
  const [ fileList, setFileList ] = useState([]);
  const users = useMappedState((state: PublicState) => state.users);
  const dispatch = useDispatch();

  // 表格结构配置
  const tableColumns = [{
    title: '姓名',
    dataIndex: 'userName',
    key: 'userName'
  }, {
    title: '手机号',
    dataIndex: 'userTel',
    key: 'userTel'
  }, {
    title: '用户类型',
    dataIndex: 'userType',
    key: 'userType',
    render: (userType: string) => {
      let userTypeText = '普通用户';
      switch (userType) {
        case '1': userTypeText = '管理员'; break;
        case '2': userTypeText = '子管理员'; break;
        case '3': userTypeText = '普通用户'; break;
        default: 
      }
      return <div>{ userTypeText }</div>
    }
  }, {
    title: '操作',
    key: 'opt',
    render: (_text: any, record: any) => {
      return [
        <Button key="edit" type="link" onClick={() => handleEditClick(record)}>编辑</Button>,
        <Button key="delete" type="link" danger onClick={() => handleDeleteClick(record)}>删除</Button>
      ]
    }
  }];

  let pagination = Object.assign({}, pageConfig);;
  if (users.res && users.res.length > 0) {
    pagination.total = users.res.length;
  }

  // 上传配置
  const uploadProps = {
    name: 'file ',
    action: `${host}/manageUser/upload?sessionKey=${localStorage.getItem('sessionKey')}`,
    maxCount: 1,
    fileList: fileList,
    accept: '.xls,.xlsx',
    onChange(info: any) {
      console.log(info);
      if (info.file.status === 'uploading') {
        setFileList(info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
        setTimeout(() => { setFileList([]); }, 1000);
        dispatch(ac_get_allusers());
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
        setTimeout(() => { setFileList([]); }, 1000);
      }
    },
  };
  
  /* --====================副作用====================-- */
  // 查询用户列表
  useEffect(() => {
    dispatch(ac_get_allusers())
  }, [dispatch]);
  
  /* --====================事件处理====================-- */
  // 删除按钮点击处理
  const handleDeleteClick = (record: any) => {
    Modal.confirm({
      title: '提示',
      content: `确认删除用户 ${record.userName} 吗？`,
      icon: <WarningOutlined />,
      onOk: () => {
        dispatch(ac_delete_user({ userTel: record.userTel }, dispatch));
      }
    })
  }

  // 修改按钮点击处理
  const handleEditClick = (record: any) => {
    dispatch(ac_set_update_user(Object.assign({}, record)));
    setIsModalVisible(true);
  }

  return (
    <div className={style.userManage}>
      <div className="btn-group">
        <Upload {...uploadProps}><Button size="middle" icon={<UploadOutlined  />} type="primary">上传用户表</Button></Upload>
      </div>
      
      <Table loading={users.usersLoading} dataSource={users.res} columns={tableColumns} pagination={pagination} rowKey={'userTel'} />

      <EditForm visible={isModalVisible} setIsModalVisible={setIsModalVisible} />
    </div>
  )
}

export default User;